import { showAlert, validNumberFromGet } from "../functionFromexport.js";

const WebApp = window.Telegram.WebApp;
WebApp.BackButton.hide();

const showPopUpPromoButton = document.querySelector(".fieldPromo");
const popUpPromo = document.getElementById("referrerPromo");

const closePromoButton = document.getElementById("closePromoButton");

let storageClientPhone = localStorage.getItem("phoneNumber");

let clientYcId = "";

if (storageClientPhone !== null && storageClientPhone !== "n/a") {
  storageClientPhone = validNumberFromGet(storageClientPhone);

  setTimeout(() => {
    fetch("/client", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ clientPhone: storageClientPhone }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        clientYcId = data[0].client_yc_id;
        copyPromo.innerText = data[0].referrer;
      });
  }, 200);
}

showPopUpPromoButton.addEventListener("click", () => {
  popUpPromo.style.display = "flex";
});

popUpPromo.addEventListener("click", (e) => {
  if (e.target.id === "referrerPromo") {
    popUpPromo.style.display = "none";
  }
});

closePromoButton.addEventListener("click", () => {
  popUpPromo.style.display = "none";
});

const innerPromoBanners = document.querySelector(".innerPromo");

fetch("/banners")
  .then((res) => res.json())
  .then((data) => {
    displayBanners(data);
  });

const displayBanners = (data) => {
  data.forEach(({ name, src, about }, index) => {
    innerPromoBanners.innerHTML += `
    <div class="slide" style="background-image: url('${src}');">
    <h2 class="h3Ower">${name}</h2>
    <p class="tooltip">${about}</p>
  </div>`;
  });
};

const openPromoMore = document.getElementById("pickPromo");
const firstFieldMain = document.getElementById("firstMain");
const secondFieldMain = document.getElementById("secondMain");

openPromoMore.addEventListener("click", () => {
  WebApp.BackButton.show();
  firstFieldMain.classList.add("classHide");
  secondFieldMain.classList.remove("classHide");
});

WebApp.BackButton.onClick(() => {
  firstFieldMain.classList.remove("classHide");
  secondFieldMain.classList.add("classHide");
  WebApp.BackButton.hide();
});

// const openRefProgram = document.getElementById("pickRefProgram");
const thirdFieldMain = document.getElementById("thirdMain");

// openRefProgram.addEventListener("click", () => {
//   if (storageClientPhone == null || storageClientPhone == "n/a") {
//     window.location.href = "/auth/";
//   } else {
//     WebApp.BackButton.show();
//     firstFieldMain.classList.add("classHide");
//     thirdFieldMain.classList.remove("classHide");
//   }
// });

WebApp.BackButton.onClick(() => {
  firstFieldMain.classList.remove("classHide");
  thirdFieldMain.classList.add("classHide");
  WebApp.BackButton.hide();
});

const fieldCopyPromo = document.querySelector(".fieldCopyPromo");
const copyPromo = document.getElementById("selfPromo");

fieldCopyPromo.addEventListener("click", function () {
  navigator.clipboard
    .writeText(copyPromo.innerText)
    .then(function () {
      showAlert("Скопированно");
    })
    .catch(function (error) {
      console.error("Error:", error);
    });
});

const shareButton = document.getElementById("share");

if (!navigator.share) {
  shareButton.classList.add("classHide");
  console.log("Ваш браузер не поддерживает эту функцию");
  fieldCopyPromo.style.marginBottom = "32px";
}

shareButton.addEventListener("click", () => {
  let textToCopy = copyPromo.innerText;
  if (navigator.share) {
    navigator
      .share({ text: `${textToCopy}` })
      .then(() => console.log("Successful share"))
      .catch((error) => console.log("Error sharing", error));
  }
});

const activPromo = document.getElementById("activationPromoBtn");
const fieldPromo = document.querySelector(".MyInput");

const errMessage = document.getElementById("errMessBonus");

fieldPromo.addEventListener("focus", () => {
  errMessage.innerText = "";
  fieldPromo.style.border = "none";
});

const displayPreloader = document.querySelector(".preloader");
const getReferrerPromo = document.getElementById("referrerPromo");
const getMainClass = document.querySelector(".main");

activPromo.addEventListener("click", () => {
  displayPreloader.style.display = "flex";
  getReferrerPromo.style.filter = "blur(5px)";
  getMainClass.style.filter = "blur(5px)";

  fetch("/promo", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ promo: fieldPromo.value, client: clientYcId }),
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      displayPreloader.style.display = "none";
      getReferrerPromo.style.filter = "";
      getMainClass.style.filter = "";
      if (data.status === 404) {
        errMessage.innerText = "Неверный код";
        fieldPromo.style.border = "1px solid red";
        // showAlert("Неверный код");
      }
      if (data.status === 409) {
        errMessage.innerText = "Промокод уже активирован";
        fieldPromo.style.border = "1px solid red";
        // showAlert("Неверный код");
      }
      if (data.status === 200) {
        fieldPromo.value = "";
        popUpPromo.style.display = "none";
        showAlert("Промокод активирован");
      }
    });
});
